package com.ycsj.goldmedalnewconcept.student.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.OnloadingMoreListener;
import com.ycsj.common.manager.BqaManager;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.manager.PopUpManager;
import com.ycsj.common.manager.SrfManager;
import com.ycsj.common.utils.ArithUtil;
import com.ycsj.common.utils.DateUtils;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.bean.ResultInfo;
import com.ycsj.goldmedalnewconcept.common.http.HttpCallBack;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.StateCodeUtils;
import com.ycsj.goldmedalnewconcept.student.adapter.DjRvAdapter;
import com.ycsj.goldmedalnewconcept.student.bean.DtInfo;
import com.ycsj.goldmedalnewconcept.student.bean.HomeInfo;
import com.ycsj.goldmedalnewconcept.student.bean.Water;
import com.ycsj.goldmedalnewconcept.view.WaterView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 朋友的宠物的家
 */
public class FriednPetHomeActivity extends BaseActivity {

    @BindView(R.id.ll_out)
    LinearLayout llOut;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_pb)
    TextView tvPb;
    @BindView(R.id.pb)
    ProgressBar pb;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_levle)
    TextView tvLevle;
    @BindView(R.id.tv_jy)
    TextView tvJy;
    @BindView(R.id.wv_water)
    WaterView waterView;
    @BindView(R.id.bt_dt)
    Button btDt;
    @BindView(R.id.lv_cw)
    ImageView lvCw;
    //内容布局
    @BindView(R.id.rl_content)
    RelativeLayout rlContent;
    //加载框布局
    @BindView(R.id.rl_loading)
    RelativeLayout rlLoading;

    //朋友的姓名和性别以及账号
    private String friendName, sex, acc2;

    //牛奶控件的数据集合
    private List<Water> mWaters;

    //请求的参数
    private String acc, role, apptoken;

    //空视图
    private View emptyView;

    //道具弹相关的视图
    private RecyclerView djRv;
    private RelativeLayout djRlLoading;

    //道具的数据
    private List<DtInfo.DataBean> djInfos;
    private DjRvAdapter djRvAdapter;
    private SmartRefreshLayout djSrf;
    //请求道具数据的翻页
    private int djPage = 0;

    //弹框相关的数据模型
    private LinearLayout llPopContent;
    private TextView tvPopName;

    //Handler对象
    private Handler handler = new Handler();

    //宠物对应的发呆和开心的gif图数据  0狗 1怪物 2老虎 3大象
    private int[] gif_fd = {R.drawable.xg_fd, R.drawable.xgw_fd, R.drawable.xlh_fd, R.drawable.xx_fd};

    //    private int[] gif_kx = {R.drawable.xg_kx, R.drawable.xgw_kx, R.drawable.xlh_kx, R.drawable.xx_kx};
    private int[] gif_kx = {R.drawable.xg_ks, R.drawable.xgw_ks, R.drawable.xlh_ks, R.drawable.xx_ks};

    //记录需要展示宠物的索引
    private int index;

    /**
     * 跳转到当前页面的方法
     *
     * @param context
     * @param name    好友的名称
     * @param acc2    好友的账号
     */
    public static void goActivity(Context context, String name, String acc2, String sex) {
        Intent intent = new Intent(context, FriednPetHomeActivity.class);
        intent.putExtra("friendname", name);
        intent.putExtra("acc2", acc2);
        intent.putExtra("sex", sex);
        context.startActivity(intent);
    }

    @Override
    protected int getContentLayout() {
        return R.layout.activity_friedn_pet_home;
    }

    @Override
    protected void init() {
        initStateBar();

        //获取Intent
        initIntent();

        //设置头数据
        initTitle();

        //设置背景数据
        initBg();

        //初始化请求参数
        initParams();

        //请求数据
        http();

    }


    /**
     * 获取Intent数据
     */
    private void initIntent() {

        //获取携带的姓名
//        friendName = getIntent().getStringExtra("friendname");
        friendName = AccountUtils.getName(this);

        //获取性别
        sex = getIntent().getStringExtra("sex");

        //获取朋友的账号
        acc2 = getIntent().getStringExtra("acc2");
    }

    /**
     * 设置背景图片
     */
    private void initBg() {
        //背景有st_home_bg 女 和friend_home_bg 男 两种
        if ("男".equals(sex)) {
            llOut.setBackgroundResource(R.drawable.friend_home_bg);
        } else if ("女".equals(sex)) {
            llOut.setBackgroundResource(R.drawable.friend_home_bg);
        } else {
            llOut.setBackgroundResource(R.drawable.friend_home_bg);
        }
    }


    /**
     * 配置请求参数
     */
    private void initParams() {

        acc = AccountUtils.getAccount(this);
        role = AccountUtils.getRole(this);
        apptoken = AccountUtils.getToken(this);
    }

    /**
     * 请求服务器数据
     */
    private void http() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "6");
        map.put("apptoken", apptoken);
        map.put("platform", "2");
        map.put("acc2", acc2);
        map.put("acc", acc);
        map.put("role", role);

//        LogUtils.iTag("test", HttpAddress.HOMEINFO + "?type=6&platform=2&apptoken=" + apptoken + "&acc2=" + acc2 + "&acc="
//                + acc + "&role=" + role);

        HttpUtils.post(HttpAddress.HOMEINFO, map, this, new HttpCallBack<HomeInfo>() {
            @Override
            public void onSuccess(HomeInfo homeInfo) {
                rlLoading.setVisibility(View.GONE);
                rlContent.setVisibility(View.VISIBLE);
                if ("200".equals(homeInfo.getState())) {
                    //设置页面数据
                    setPageData(homeInfo);
                } else if ("104".equals(homeInfo.getState())) {
                    //没有可采集牛奶的数据
                    setPetInfo(homeInfo);
                } else {
                    ToastUtils.showShort(BaseApplication.STATEERROE + homeInfo.getState());
                }
            }

            @Override
            public void onError(String e) {
                rlLoading.setVisibility(View.GONE);
                ToastUtils.showShort(BaseApplication.ERROR);
            }
        });
    }


    /**
     * 设置页面数据
     *
     * @param homeInfo
     */
    private void setPageData(HomeInfo homeInfo) {

        //设置宠物信息
        setPetInfo(homeInfo);

        //设置未收取的牛奶数据
        List<HomeInfo.DataBean> data = homeInfo.getData();
        if (data == null || data.size() == 0) {
            //表示没有收取的牛奶
            waterView.setVisibility(View.GONE);
        } else {
            waterView.setVisibility(View.VISIBLE);
            mWaters = new ArrayList<>();
            for (int i = 0; i < data.size(); i++) {
                Water water = new Water();
                water.setId(data.get(i).getId());
                water.setMilkBeginTime(data.get(i).getMilkBeginTimeStr());
                water.setMilkEndTime(data.get(i).getMilkEndTimeStr());
                water.setName(data.get(i).getMilkName());
                water.setNumber(Integer.parseInt(data.get(i).getMilkMass()));
                mWaters.add(water);
            }
            waterView.setWaters(mWaters);
            waterView.setOnWaterClickListener(new WaterView.onWaterClickListener() {
                @Override
                public void onWaterClick(Water water, View view) {

                    //请求服务器领取牛奶
                    httpGetMilkAciton(water, view);
                }
            });

        }
    }


    /**
     * 设置宠物的相信信息
     *
     * @param homeInfo
     */
    private void setPetInfo(HomeInfo homeInfo) {
        //根据宠物的id设置宠物
        String petId = homeInfo.getPET_ID();
        //判断是否需要展示GIF
        if ("1".equals(homeInfo.getHasGif())) {

            //设置展示道具Gif的ImageView的大小和定时取消
            sysCwState(petId, homeInfo.getPetGifEndTime());

        } else {
            //没有道具,需要加载默认的Gif图片''
            index = Integer.parseInt(petId);
            setLvCwParams(UiUtils.dp2px(220), UiUtils.dp2px(220));
            Glide.with(this).load(gif_fd[index]).into(lvCw);
        }

        //设置宠物名称,等级,进度以及牛奶数量
        String nickName = homeInfo.getNICK_NAME();
        tvName.setText(nickName);

        //获取宠物的等级
        String petLevel = homeInfo.getLEVEL();
        tvLevle.setText("Lv." + petLevel);

        //获取当前的牛奶
        String currMilk = homeInfo.getMILK();

        //获取升下一级需要的牛奶
        String nextMilk = homeInfo.getNEXT_MILK();
        tvPb.setText(currMilk + "/" + nextMilk);

        //设置进度
        pb.setProgress(ArithUtil.bs(Integer.parseInt(currMilk), Integer.parseInt(nextMilk)));

        //获取总的牛奶数
        String milk = homeInfo.getMILK();
        tvJy.setText(milk + "g");
    }

    /**
     * 设置展示宠物的ImageView的布局参数
     */
    private void setLvCwParams(int width, int height) {
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(width, height);
        lp.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
        lp.bottomMargin = UiUtils.dp2px(26);
        lvCw.setLayoutParams(lp);
    }

    /**
     * 使用道具后同步展示宠物Gif动图
     */
    private void sysCwState(final String petGifType, String petGifEndTime) {
        handler.removeCallbacksAndMessages(null);

        //Gif图需要显示的图片比较大
        setLvCwParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        index = Integer.parseInt(petGifType);

        //表示有道具,需要显示Gif图
        Glide.with(this).load(gif_kx[index]).into(lvCw);

        //获取Gif图结束时间与当前系统时间差
        long time = DateUtils.getTime(petGifEndTime, "yyyy-MM-dd HH:mm:ss") - System.currentTimeMillis();

        //当道具的Gif到时间后不在显示道具的Gif图,而是显示默认的Gif图
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Glide.with(FriednPetHomeActivity.this).load(gif_fd[index]).into(lvCw);
            }
        }, time);
    }

    /**
     * 领取好友的牛奶
     *
     * @param water
     */
    private void httpGetMilkAciton(Water water, final View view) {
        CustomDialogManager.show(this, "领取中...");
        Map<String, String> map = new HashMap<>();
        map.put("type", "3");
        map.put("acc", acc);
        map.put("role", role);
        map.put("apptoken", apptoken);
        map.put("platform", "2");
        map.put("id", water.getId());
        map.put("friend", acc2);
        map.put("name", friendName);
        HttpUtils.post(HttpAddress.GETFRIENDMILK, map, this, new HttpCallBack<ResultInfo>() {
            @Override
            public void onSuccess(ResultInfo resultInfo) {
                CustomDialogManager.dissmiss();
                if ("200".equals(resultInfo.getState())) {
//                    ToastUtils.showShort("领取成功");
                    //领取成功后执行消失的动画
                    waterView.handViewClick(view);
                    //刷新状态
                    http();
                } else {
                    StateCodeUtils.showSateCode(resultInfo.getState());
                }
            }

            @Override
            public void onError(String e) {
                CustomDialogManager.dissmiss();
                ToastUtils.showShort(BaseApplication.ERROR + ",领取失败");
            }
        });
    }


    /**
     * 设置头数据
     */
    private void initTitle() {
        //设置标题
        if (!TextUtils.isEmpty(friendName)) {
            tvTitle.setText(friendName + "的家");
        }
    }


    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.iv_back, R.id.bt_dt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                //返回
                finish();
                break;
            case R.id.bt_dt:
                //动态弹框
                showDjPop();
                break;
        }
    }

    /**
     * 动态的弹框
     */
    private void showDjPop() {
        //请求服务器的道具数据
        PopUpManager.showPop(this, R.layout.pop_gy, 0.3f, new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {
                //下拉刷新
                djSrf = view.findViewById(R.id.srf);

                //内容布局
                llPopContent = view.findViewById(R.id.ll_content);

                //标题
                tvPopName = view.findViewById(R.id.tv_name);
                tvPopName.setText("动态");

                SrfManager.setSmartByPullListener(djSrf, new SrfManager.OnPullRefreshListener() {
                    @Override
                    public void onRefresh(RefreshLayout refreshlayout) {
                        //下拉刷新
                        HttpDj(BqaManager.PULLREFRESH);
                    }
                });
                //关闭按钮
                ImageView lvClose = view.findViewById(R.id.lv_close);

                lvClose.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        PopUpManager.dismiss();
                    }
                });

                //列表控件
                djRv = view.findViewById(R.id.rv);

                //加载框布局
                djRlLoading = view.findViewById(R.id.rl_loading);

                //加载的空视图
                emptyView = View.inflate(FriednPetHomeActivity.this, R.layout.base_rv_common_empty_view_white_bg, null);
                djInfos = new ArrayList<>();
                djRvAdapter = new DjRvAdapter(R.layout.item_rv_dj, djInfos);

                //请求数据
                HttpDj(BqaManager.NORML);
            }
        });
    }

    /**
     * 请求道具的数据
     *
     * @param method
     */
    private void HttpDj(final int method) {
        if (method == BqaManager.NORML || method == BqaManager.PULLREFRESH) {
            djPage = 0;
        } else {
            djPage++;
        }

        Map<String, String> map = new HashMap<>();
        map.put("type", "7");
        map.put("acc", acc);
        map.put("role", role);
        map.put("apptoken", apptoken);
        map.put("platform", "2");
        map.put("page", djPage + "");
        map.put("size", 5 + "");
        map.put("friend", acc2);

        HttpUtils.post(HttpAddress.DJDATA, map, this, new HttpCallBack<DtInfo>() {
            @Override
            public void onSuccess(DtInfo info) {
                djRlLoading.setVisibility(View.GONE);
                llPopContent.setVisibility(View.VISIBLE);
                if ("200".equals(info.getState())) {
                    List<DtInfo.DataBean> newDatas = info.getData();
                    if (method == BqaManager.NORML) {
                        if (newDatas != null && newDatas.size() != 0) {
                            djInfos.addAll(newDatas);
                        }
                        BqaManager.setRv(emptyView, FriednPetHomeActivity.this, djRvAdapter, djRv, new OnloadingMoreListener() {
                            @Override
                            public void onLoadMore() {
                                HttpDj(BqaManager.LOADINDGMORE);
                            }
                        });
                    } else {
                        BqaManager.updateRvBySmf(method, djSrf, djRv, djInfos, newDatas, djRvAdapter);
                    }
                } else if ("104".equals(info.getState())) {
                    //没查询到数据
                    if (method == BqaManager.LOADINDGMORE) {
                        //结束加载更多
                        djRvAdapter.loadMoreEnd();
                    } else if (method == BqaManager.NORML) {
                        BqaManager.setRv(emptyView, FriednPetHomeActivity.this, djRvAdapter, djRv, new OnloadingMoreListener() {
                            @Override
                            public void onLoadMore() {
                                HttpDj(BqaManager.LOADINDGMORE);
                            }
                        });
                    } else if (method == BqaManager.PULLREFRESH) {
                        if (djSrf != null) {
                            djSrf.finishRefresh();
                        }
                        djInfos.clear();
                        djRvAdapter.notifyDataSetChanged();
                    }
                } else {
                    ToastUtils.showShort(BaseApplication.STATEERROE + info.getState());
                }
            }

            @Override
            public void onError(String e) {
                djRlLoading.setVisibility(View.GONE);
                ToastUtils.showShort(BaseApplication.ERROR);
            }
        });

    }

    @Override
    protected void onDestroy() {
        if (null != handler) {
            handler.removeCallbacksAndMessages(null);
        }
        super.onDestroy();
    }

}
